package com.huiquan.framework.utils;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;

/**
 * @ClassName: ReturnUtil
 * @author 作者
 * @Description: 接口返回工具类
 * @date 2015年1月24日 下午8:09:30
 * @version V1.0
 */
public class ReturnUtil {

	private static Logger log = LogManager.getLogger(ReturnUtil.class.getName());

	public static ReturnData fail(BindingResult br) {
		FieldError fe = null;

		String paramErrors = "";

		for (int i = 0; i < br.getFieldErrors().size(); i++) {
			fe = br.getFieldErrors().get(i);

			paramErrors += "; " + fe.getDefaultMessage() + ": " + fe.getField();
		}

		log.error(paramErrors.substring(2));

		ReturnData returnData = ReturnUtil.fail(ReturnCode.PARAM);
		returnData.getData().put("msg", paramErrors.substring(2));
		return returnData;
	}

	public static ReturnData fail(ReturnCode rc) {
		Map<String, Object> data = new HashMap<String, Object>();

		log.info(rc);

		return new ReturnData(rc, data);
	}

	public static ReturnData fail(ReturnCode rc, Map<String, Object> data) {
		log.info(rc);

		return new ReturnData(rc, data);
	}

	public static ReturnData success() {
		Map<String, Object> data = new HashMap<String, Object>();

		return new ReturnData(ReturnCode.SUCCESS, data);
	}

	public static ReturnData success(String msg) {
		Map<String, Object> data = new HashMap<String, Object>();
		ReturnCode returncode = ReturnCode.SUCCESS;
		returncode.setDesc(msg);

		return new ReturnData(returncode, data);
	}

	public static ReturnData success(Map<String, Object> data) {
		return new ReturnData(ReturnCode.SUCCESS, data);
	}

	/**
	 * 自定义返回消息
	 * 
	 * @param message
	 * @return
	 */
	public static ReturnData customMessage(String message) {
		Map<String, Object> map = new HashMap<>();
		ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
		returnCode.setDesc(message);
		return new ReturnData(returnCode, map);
	}

	/**
	 * 自定义返回消息
	 * 
	 * @param message
	 * @param map
	 * @return
	 */
	public static ReturnData customMessage(String message, Map<String, Object> map) {
		ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
		returnCode.setDesc(message);
		return new ReturnData(returnCode, map);
	}

}